package crafex.engine.system;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import crafex.engine.level.Level;
import crafex.engine.tools.Tools;



public class SavingSystem {
	static FileOutputStream f_out;
	static ObjectOutputStream obj_out;
	static FileInputStream f_in;
	static ObjectInputStream obj_in;
	static BufferedWriter buf_writer;
	static BufferedReader buf_reader;
	
	public static void saveGame(Level game, String saveName) throws IOException{
		f_out = new 
			FileOutputStream(Tools.getSavePath() + saveName + ".data");

		obj_out = new
			ObjectOutputStream (f_out);

		obj_out.writeObject (game);
		
		obj_out.close();
	}
	
	public static Level loadGame(String saveName) throws IOException, ClassNotFoundException{
		f_in = new 
				FileInputStream(Tools.getSavePath() + saveName + ".data");
		
		obj_in = new 
				ObjectInputStream(f_in);
		
		return (Level) obj_in.readObject();
	}
	
	public static void saveList(String saveName, Object[] list, String[] nameList) throws IOException{
		File file = new File(Tools.getSavePath() + saveName + ".data");
		buf_writer = new BufferedWriter(new FileWriter(file));
			
		for(int i = 0; i < list.length; i++){
			if(nameList.length > i){
				if(i != 0){
					buf_writer.newLine();
				}
				buf_writer.write("-" + nameList[i] + "=" + list[i].toString());
			}
		}
		buf_writer.close();
	}
	
	public static Object[] loadList(String saveName) throws IOException{
		File file = new File(Tools.getSavePath() + saveName + ".data");
		buf_reader = new BufferedReader(new FileReader(file));
		ArrayList<String> buffer = new ArrayList<String>();
		
		for(String lineBuffer; (lineBuffer = buf_reader.readLine()) != null;) {
            buffer.add(lineBuffer);
        }
		
		String[] data = buffer.toArray(new String[buffer.size()]);
		
		for(int i = 0; i < data.length; i++){
			System.out.println(data[i]);
		}
		
		return data;
	}
	
}
